<?php 
if (!defined('BASEPATH')){
	exit('No direct script access allowed');
}

/**
 * flyTomorrow Controller
 * Build by Phuc Nguyen
 * Contact : nguyenvanphuc0626@gmail.com
 */

class FlyTomorrow extends BACKEND_Controller {
	public function __construct() {
		parent::__construct();
		$this->load->language('flyTomorrow');
		$this->load->language('button');
		if($this->database_connect_status){
			$this->load->model('flyTomorrow_model');
			$this->set_controller('flyTomorrow');
			$this->set_model($this->flyTomorrow_model);
		}
                $this->load->model('flyTomorrow_model');

                $this->load->library('bookinglib');
                $this->bookinglib = new bookinglib();
	}
        
        private function menuTop(){
            $this->load->model('stats_model');
            $user_info                          = $this->stats_model->get_user_info($this->stats_model->get_user_id());
            $this->view_data['role_by_group']   = $user_info['role_list'];
            $this->view_data['username']        = $user_info['username'];
            return $this->view_data;
        }
        
        private function direct(){
            $checkDirect = $_SERVER['HTTP_REFERER'];
            if(!isset($checkDirect)){
                redirect(base_url());
            }
        }
        
        public function updateApiStatusCall(){
            $this->flyTomorrow_model->updateApiStatusCall($this->session->userdata['user_id'],1);
        }

        public function updateStatus(){
            if($this->input->server('REQUEST_METHOD')=='POST'){
                $this->view_data["flyTomorrows"]                                     = new stdClass();
                $this->view_data["flyTomorrows"]->status                             = $this->input->post('status');
                $this->view_data["flyTomorrows"]->owner                              = $this->session->userdata['user_id'];

                $query = $this->flyTomorrow_model->update($this->view_data["flyTomorrows"],trim($this->input->post('id')));
            }
        }
        
        public function display(){
            
                    $prevent            = $this->flyTomorrow_model->find_by(array('status'=>'1','owner'=>$this->session->userdata['user_id']));
                    if($prevent){
                        echo '<script>alert("'.$this->lang->line('preventMutiTab').'");window.top.location.href="/auth/flyTomorrow/";</script>';exit;
                    }
                    
                    $flyTomorrow_query	= $this->flyTomorrow_model->find_by(array('id' => $this->input->get('id'),'status'=>'0'));
                    
                    if(empty($flyTomorrow_query)){
                       echo '<script>alert("'.$this->lang->line('used_calling').'");window.top.location.href="/auth/flyTomorrow/";</script>';exit;
                    } else {
                        $this->load->model("bookhistory_model");
                        $booking 	= $this->bookhistory_model->find_by(array('booking_place_code'=>$flyTomorrow_query[0]->booking_place_code));
                        $ship 		= $this->exportShipName($booking[0]->booking);
						
                        $this->load->model("listcustomers_model");
                        $info_user                                                  = $this->listcustomers_model->find_by(array('customerID' => $flyTomorrow_query[0]->customerID));
                        $flyTomorrow_query[0]->name                                 = $info_user[0]->name;
                        $flyTomorrow_query[0]->phone                                = json_decode($flyTomorrow_query[0]->phone);
                        $flyTomorrow_query[0]->ship				= implode("\n",$ship);
                        $flyTomorrow_query[0]->dkve				= $booking[0]->dkve;
                        $flyTomorrow_query[0]->dkhanhly				= $booking[0]->dkhanhly;
						
                        $this->view_data['flyTomorrow']                             = $flyTomorrow_query[0];
                        
                        $this->view_data["data"]                                        = new stdClass();
                        $this->view_data["data"]->status                                = 1;
                        $this->view_data["data"]->owner                                 = $this->session->userdata['user_id'];
                        $this->view_data["data"]->booking_place_code                    = $flyTomorrow_query[0]->booking_place_code;
                        $this->view_data["data"]->customerID                            = $flyTomorrow_query[0]->customerID;
                        
                        $this->flyTomorrow_model->update($this->view_data["data"],trim($this->input->get('id')));
                        unset($this->view_data["data"]);
                    }
                    
                    $json 		= $this->apiCallShip(array('booking_place_code'=>$booking[0]->booking_place_code,'airline'=>$booking[0]->airline));
                    $json 		= json_decode($json);
                    $this->view_data["flyTomorrow"]->loadship				= implode("\n",$json);
					//print_r($this->view_data["flyTomorrow"]->loadship);exit;
                    $this->view_data['js'] = array(
                            base_url().'static/templates/backend/js/main.js'
                    );
                    $this->view_data['css'] = array(
                    );

                    $this->load->view('auth/flyTomorrow/edit', $this->view_data);
        }
		
        public function apiCallShip($params){
            $params = array(
                'sdata'             =>  $params['booking_place_code'],
                'sairlines'         =>  $params['airline']
            );
            $json = json_decode(file_get_contents('http://192.168.1.232/vbapi/do_process.php?sdata='.$params['sdata'].'&sairlines='.$params['sairlines']));
            $ship = '';
            $this->load->model('bookairport_model');
            if($json->flight){
                foreach($json->paxname as $keys => $vals){
                    $ship[] = trim($vals);
                }
                foreach($json->flight as $key => $val){
                    $datetime 	= explode("/",$val->ngaybay);
                    $expsbdi 	= explode("&nbsp;",$val->sbdi);
                    $expsbden 	= explode("&nbsp;",$val->sbden);
                    $sbdi           = $this->bookairport_model->find_by(array('code'=>trim($expsbdi[1])));
                    $sbden          = $this->bookairport_model->find_by(array('code'=>trim($expsbden[1])));				
                    $ship[]         = preg_replace('/\s+/', '', $val->sohieu).' '.trim($datetime[0]).'.'.trim($datetime[1]).' '.$sbdi[0]->cityEn.' '.$sbden[0]->cityEn.' '.trim($expsbdi[0]);
                }
            }
            return json_encode($ship);
        }//loadShip
        
        public function updateInfo(){
            
            $this->direct();//prevent direct
            if($this->input->server('REQUEST_METHOD')=='POST'){
                $this->view_data["data"]                                        = new stdClass();
                $this->view_data["data"]->phone_callstatus                      = $this->input->post('phone_callstatus');
                $this->view_data["data"]->status                                = 0;
                $this->view_data["data"]->note                                  = $this->input->post('note');
                
                $phone_calltime = $this->checkVoiceIp(trim($this->input->post('phone')));
                if($phone_calltime){
                    $this->view_data["data"]->phone_calltime                    = $phone_calltime;
                } else {
                    $this->view_data["data"]->phone_calltime                    = 0;
                }
                //$this->flyTomorrow_model
                $data = array('data'=>$this->view_data["data"],'customerID'=>$this->input->post('customerID'),'booking_place_code'=>$this->input->post('booking_place_code'),'airline'=>$this->input->post('airline'));
                
                $result = $this->flyTomorrow_model->updateAllCus($data);
                
//                $this->flyTomorrow_model->update($this->view_data["data"],trim($this->input->post('id')));
                die("1");
            }
            die("");
        }
        
        public function checkVoiceIp($param) {
            if(in_array($this->session->userdata['user_id'],array('152','166','168','169'))){
                $phone      = $param;
                $xml        = simplexml_load_file(VOICE_IP_API.$phone);
                $arr        = $this->toArray($xml->user);
                
                return ($arr['Thoigiangoi'])?$arr['Thoigiangoi']:'';
            } else {
                //trường hợp k dùng voiceIp thì k làm gì
                return '';
            }
        }
        
        function toArray(SimpleXMLElement $xml) {
            $array = (array)$xml;

            foreach ( array_slice($array, 0) as $key => $value ) {
                if ( $value instanceof SimpleXMLElement ) {
                    $array[$key] = empty($value) ? NULL : toArray($value);
                }
            }
            return $array;
        }
		
        public function exportShipName($params){
            $noidung                        = array();
            $this->load->model('bookairport_model');
			
            foreach(json_decode($params) as $key => $vals){
                $info       = explode("-", $vals);
                $sbdi       = $this->bookairport_model->find_by(array('code'=>trim($info[3])));
                if(empty($sbdi)){
                        $content               = json_decode(file_get_contents(PRE_API_AIRPORT.trim($info[3]).'?isDestination=false&ccy=VND'));
                        $_info      = array(
                            'code'         =>  trim($content[0]->PlaceId),
                            'city'         =>  trim($content[0]->CityName),
                            'cityEn'       =>  trim(str_replace("City", "", $content[0]->CityNameEn)),
                            'country'      =>  trim($content[0]->CountryName),
                            'countryEn'    =>  trim($content[0]->CountryName)
                        );
                        $this->bookairport_model->create($_info);
                        unset($_info);unset($content);
                }
                $sbdi       = trim($sbdi[0]->cityEn);
                $sbden      = $this->bookairport_model->find_by(array('code'=>trim($info[5])));

                if(empty($sbden)){
                        $content               = json_decode(file_get_contents(PRE_API_AIRPORT.trim($info[5]).'?isDestination=false&ccy=VND'));
                        $_info      = array(
                            'code'         =>  trim($content[0]->PlaceId),
                            'city'         =>  trim($content[0]->CityName),
                            'cityEn'       =>  trim(str_replace("City", "", $content[0]->CityNameEn)),
                            'country'      =>  trim($content[0]->CountryName),
                            'countryEn'    =>  trim($content[0]->CountryName)
                        );
                        $this->bookairport_model->create($_info);
                        
                        unset($_info);unset($content);
                }
                $sbden          = trim($sbden[0]->cityEn);
                $times          = explode('/', $info[0]);
                $noidung[]      .= $info[1].' '.$times[0].'.'.$times[1].' '.$sbdi.' '.$sbden.' '.$info[2];
            }	
            return $noidung;
        }
}